//
//  GabberAppDelegate.m
//  Gabber
//
//  Created by 陆惠国 on 11-8-23.
//  Copyright 2011年 恒生聚源. All rights reserved.
//

#import "AppDelegate.h"

// #import "UIApplication+ScreenMirroring.h"
#import "DDLog.h"
#import "XMPPClient.h"
#import "DDTTYLogger.h"
#import "StyleSheet.h"
#import "RootViewController.h"
#import "SplitRootViewController.h"
#import "LoginViewController.h"
#import "RosterViewController.h"
#import "ChatViewController.h"
#import "AboutViewController.h"
#import "SettingsViewController.h"
#import "MessagesViewController.h"
#import "CardViewController.h"

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);    
    
    UIDevice* device = [UIDevice currentDevice];
	BOOL backgroundSupported = NO;
	if ([device respondsToSelector:@selector(isMultitaskingSupported)])
		backgroundSupported = device.multitaskingSupported;
	
	DDLogVerbose(@"backgroundSupported[%@]",backgroundSupported ? @"YES" : @"NO");	
    
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
	_hostReach = [[Reachability reachabilityWithHostname: @"www.gildata.com"] retain];
	[_hostReach startNotifier];
    _internetReach = [[Reachability reachabilityForInternetConnection] retain];
	[_internetReach startNotifier];
    _wifiReach = [[Reachability reachabilityForLocalWiFi] retain];
	[_wifiReach startNotifier];
    
    TTNavigator* navigator = [TTNavigator navigator];
    navigator.supportsShakeToReload = NO;
    navigator.persistenceMode = TTNavigatorPersistenceModeNone;
    
    navigator.window = [[[UIWindow alloc] initWithFrame:TTScreenBounds()] autorelease];
    
    
    [TTStyleSheet setGlobalStyleSheet:[[[StyleSheet alloc] init] autorelease]];
    
    TTURLMap* map = navigator.URLMap;
    [map from:@"*" toViewController:[TTWebController class]];   
    [map from:@"gabber://login" toSharedViewController:[LoginViewController class]];
    if (TTIsPad()) {
        [map from:@"gabber://root" toSharedViewController:[SplitRootViewController class]];
        [map from:@"gabber://vcard/(initWithJidStr:)" toPopoverViewController:[CardViewController class]];
        [map from:@"gabber://about" toPopoverViewController:[AboutViewController class]];  
        [map from:@"gabber://settings" toPopoverViewController:[SettingsViewController class]];  


    } else {
        [map from:@"gabber://root" toSharedViewController:[RootViewController class]];
        [map from:@"gabber://about" toSharedViewController:[AboutViewController class]];  
        [map from:@"gabber://settings" toSharedViewController:[SettingsViewController class]];   
        [map from:@"gabber://messages" toSharedViewController:[MessagesViewController class]];   
        [map from:@"gabber://roster" toSharedViewController:[RosterViewController class]];
        [map from:@"gabber://chat/(initWithJidStr:)" toModalViewController:[ChatViewController class]];
        [map from:@"gabber://vcard/(initWithJidStr:)" toViewController:[CardViewController class]];
    }

 
    

      
//    [map from:@"gabber://nib/(loadFromNib:)" toSharedViewController:self];
//    [map from:@"gabber://nib/(loadFromNib:)/(withClass:)" toSharedViewController:self];
//    [map from:@"gabber://viewController/(loadFromVC:)" toSharedViewController:self];
//    [map from:@"gabber://modal/(loadFromNib:)" toModalViewController:self];
    

    if (![navigator restoreViewControllers]) {        
        [navigator openURLAction:[TTURLAction actionWithURLPath:@"gabber://login"]];
    }    
    
    //[[UIApplication sharedApplication] setupScreenMirroring];

    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
    [[XMPPClient sharedInstance] goAway]; 
    [[XMPPClient sharedInstance] saveAll];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
	DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    [[XMPPClient sharedInstance] goAway]; 
    [[XMPPClient sharedInstance] saveAll];    
//#if TARGET_IPHONE_SIMULATOR
//	DDLogError(@"The iPhone simulator does not process background network traffic. "
//			   @"Inbound traffic is queued until the keepAliveTimeout:handler: fires.");
//#endif
//    
//	if ([application respondsToSelector:@selector(setKeepAliveTimeout:handler:)]) 
//	{
//		[application setKeepAliveTimeout:600 handler:^{
//			
//			DDLogVerbose(@"KeepAliveHandler");
//			
//			// Do other keep alive stuff here.
//		}];
//	}    
    
    NSAssert(_bgTask == UIBackgroundTaskInvalid, nil);
	
	_bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
		// Synchronize the cleanup call on the main thread in case
		// the task catully finished at around the same time.
		dispatch_async(dispatch_get_main_queue(), ^{
			
			if (UIBackgroundTaskInvalid != _bgTask) {
				
				[application endBackgroundTask:_bgTask];
				_bgTask = UIBackgroundTaskInvalid;
			}
		});
	}];
	
	// Start the long-running task and return immediately.
	dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
				   ^{
					   // Do the work assoicated with the task.
					   DDLogVerbose(@"Time Remain = %f", [application backgroundTimeRemaining]);
                       [application endBackgroundTask:_bgTask];
                       _bgTask = UIBackgroundTaskInvalid;
                       
					   // Synchronize the cleanup all on the main thread in case
					   // the task catully finished at around the same time. 
//					   dispatch_async(dispatch_get_main_queue(), ^{
//						   
//						   if (UIBackgroundTaskInvalid != _bgTask) {
//                               
//							   [application endBackgroundTask:_bgTask];
//							   _bgTask = UIBackgroundTaskInvalid;
//						   }
//					   });
				   });

    
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */

    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    [[XMPPClient sharedInstance] goOnline]; 
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    [[XMPPClient sharedInstance] goOnline]; 
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [[XMPPClient sharedInstance] saveAll];

    
    
    [[XMPPClient sharedInstance] disconnect];
    
    //[[[XMPPClient sharedInstance] xmppvCardTempModule] removeDelegate:self];
  
}

- (void)dealloc
{

    [super dealloc];
}


///////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * Loads the given viewcontroller from the nib
 */
- (UIViewController*)loadFromNib:(NSString *)nibName withClass:className {
    UIViewController* newController = [[NSClassFromString(className) alloc]
                                       initWithNibName:nibName bundle:nil];
    [newController autorelease];
    
    return newController;
}


///////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * Loads the given viewcontroller from the the nib with the same name as the
 * class
 */
- (UIViewController*)loadFromNib:(NSString*)className {
    return [self loadFromNib:className withClass:className];
}


///////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * Loads the given viewcontroller by name
 */
- (UIViewController *)loadFromVC:(NSString *)className {
    UIViewController * newController = [[ NSClassFromString(className) alloc] init];
    [newController autorelease];
    
    return newController;
}


///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)URL {
    [[TTNavigator navigator] openURLAction:[TTURLAction actionWithURLPath:URL.absoluteString]];
    return YES;
}



#pragma mark - Reachability

//Called by Reachability whenever status changes.
- (void) reachabilityChanged: (NSNotification* )note
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);     
	Reachability* curReach = [note object];
	NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    
    switch ([curReach currentReachabilityStatus]) {
        case NotReachable:
			DDLogInfo(@"Reachability: %@",  @"NotReachable");
            break;
        case ReachableViaWWAN:
            DDLogInfo(@"Reachability: %@",  @"ReachableViaWWAN");
            break;
        case ReachableViaWiFi:
            DDLogInfo(@"Reachability: %@",  @"ReachableViaWiFi");   
            break;
    }
    
	
}

@end
